const Service = require('egg').Service
const schedule = require('node-schedule')

class CourseCommentService extends Service {
  async index(courseId) {
    const { ctx, app } = this
    // 获取当前课程讨论
    const commentRes = await ctx.find('CourseComment', { where: { courseId }}, 'findAll')
    const tmp = []
    if (commentRes.length > 0) {
      commentRes.forEach(item => {
        tmp.push(item.dataValues)
      })
    }
    const commentUrl = `${app.config.moocDomain}/web/j/mocCourseV2RpcBean.getCourseEvaluatePaginationByCourseIdOrTermId.rpc?csrfKey=${app.config.moocCookie.NTESSTUDYSI}`
    let curIndex = 1
    const job = schedule.scheduleJob('*/3 * * * * *', async() => {
      const res = await ctx.helper.curlPost(commentUrl, {
        courseId,
        pageIndex: curIndex,
        pageSize: 30,
        orderBy: 3
      })
      const data = res.data
      if (data.code === 0) {
        if (data.result && data.result.list.length > 0) {
          this.createComment(data.result.list, courseId, tmp)
        } else {
          console.log('数据爬取完毕')
          job.cancel()
        }
      } else {
        console.log('接口出现异常')
        job.cancel()
      }
      curIndex++
    })
  }

  async createComment(data, courseId, comments) {
    const { ctx } = this
    const postData = []
    data.forEach(item => {
      const { id, content, mark, agreeCount, userNickName, faceUrl } = item
      const dict = {
        commentId: id,
        courseId,
        faceUrl,
        content,
        mark,
        agreeCount,
        userNickname: userNickName
      }
      const index = comments.findIndex(comment => +comment.commentId === id)
      if (index !== -1) {
        if (+comments[index].mark !== +mark || +comments[index].agreeCount !== +agreeCount) {
          dict.id = comments[index].id
          postData.push(dict)
        }
      } else {
        postData.push(dict)
      }
    })
    await ctx.bulkCreate('CourseComment', postData, { updateOnDuplicate: ['agreeCount', 'mark'] })
  }
}

module.exports = CourseCommentService
